#include "ZigbeeWidget.h"
#include "ui_ZigbeeWidget.h"
#include <QMessageBox>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    /*
    *    设置窗口标题、大小，固定
    */
    Qt::WindowFlags flags = 0;
    flags |= Qt::WindowMinimizeButtonHint;
    flags |= Qt::WindowMaximizeButtonHint;
    setWindowFlags(flags); // 设置禁止最大化
    setFixedSize(1010,670); // 禁止改变窗口大小。
    this->setWindowTitle(QString("zigbee配置软件"));

/*******************初始界面内容*****************************/
    ui->RouterNodeType->setDisabled(true);
    ui->RouterPanIdOne->setDisabled(true);
    ui->RouterPanIdTwo->setDisabled(true);
    ui->RouterChannel->setDisabled(true);

    ui->WriteNodeType->setCurrentIndex(1);
    ui->RouterNodeType->setCurrentIndex(1);
    ui->WriteBuadRate->setCurrentIndex(5);
    ui->RouterBuadRate->setCurrentIndex(5);

    ui->WritePinIdOne->setText("2A");
    ui->WritePinIdTwo->setText("01");
    ui->RouterPanIdOne->setText("2A");
    ui->RouterPanIdTwo->setText("01");
    ui->WriteAddrOne->setText("10");
    ui->WriteAddrTwo->setText("11");
    ui->RouterAddrOne->setText("0A");
    ui->RouterAddrTwo->setText("0B");
/*******************初始界面内容结束*****************************/

    mMessageQueue = new MessageQueue(this);
    mWorkThread = new WorkThread(this);
    mWorkThread->startWork();
}

Widget::~Widget()
{
    delete mWorkThread;
    delete mMessageQueue;
    delete ui;
}

void Widget::on_ConnectButton_clicked()
{
    if (mMessageQueue->messageIsBusy()) {
        qDebug("[on_ConnectButton_clicked] thread is busy! do not response!");
        return;
    }
    mMessageQueue->sendMessage(MessageQueue::MESSAGE_CONNECT);

    QString mytext = this->ui->RouterBuadRate->currentText();
    int ind =this->ui->RouterBuadRate->currentIndex();
    qDebug("ind:%d,string:%s",ind,mytext.toLocal8Bit().constData());
}

void Widget::on_ReadButton_clicked()
{
    if (mMessageQueue->messageIsBusy()) {
        qDebug("[on_ReadButton_clicked] thread is busy! do not response!");
        return;
    }
    mMessageQueue->sendMessage(MessageQueue::MESSAGE_READ_INFO);
}

void Widget::on_HelpButton_clicked()
{

}

void Widget::on_WriteButton_clicked()
{
    if (mMessageQueue->messageIsBusy()) {
        qDebug("[on_WriteButton_clicked] thread is busy! do not response!");
        return;
    }
    mMessageQueue->sendMessage(MessageQueue::MESSAGE_WRITE_ARG);
}

void Widget::on_ResetButton_clicked()
{
    if (mMessageQueue->messageIsBusy()) {
        qDebug("[on_ResetButton_clicked] thread is busy! do not response!");
        return;
    }
    mMessageQueue->sendMessage(MessageQueue::MESSAGE_RESET);
}


void Widget::on_WriteNodeType_currentIndexChanged(int index)
{
    ui->RouterNodeType->setCurrentIndex(index);
}


void Widget::on_WriteChannel_currentIndexChanged(int index)
{
    ui->RouterChannel->setCurrentIndex(index);
}


void Widget::on_WritePinIdOne_editingFinished()
{
    qDebug("[on_WritePinIdOne_editingFinished] edit end!");
    QString mText = ui->WritePinIdOne->text();
    if (!checkNumCorrect(mText)) {
        qDebug("[on_WritePinIdOne_editingFinished] error text:%s",mText.toLocal8Bit().constData());
        QMessageBox::warning(0,"WARNING","PIN ID ERROR!",QMessageBox::Yes);
        return;
    }
    ui->RouterPanIdOne->setText(mText);
}

void Widget::on_WritePinIdTwo_editingFinished()
{
    qDebug("[on_WritePinIdTwo_editingFinished] edit end!");
    QString mText = ui->WritePinIdTwo->text();
    if (!checkNumCorrect(mText)) {
        qDebug("[on_WritePinIdTwo_editingFinished] error text:%s",mText.toLocal8Bit().constData());
        QMessageBox::warning(0,"WARNING","PIN ID ERROR!",QMessageBox::Yes);
        return;
    }
    ui->RouterPanIdTwo->setText(mText);
}

void Widget::on_WriteAddrOne_editingFinished()
{
    qDebug("[on_WriteAddrOne_editingFinished] edit end!");
    QString mText = ui->WriteAddrOne->text();
    if (!checkNumCorrect(mText)) {
        qDebug("[on_WriteAddrOne_editingFinished] error text:%s",mText.toLocal8Bit().constData());
        QMessageBox::warning(0,"WARNING","ADDRING ERROR!",QMessageBox::Yes);
        return;
    }
}

void Widget::on_WriteAddrTwo_editingFinished()
{
    qDebug("[on_WriteAddrTwo_editingFinished] edit end!");
    QString mText = ui->WriteAddrTwo->text();
    if (!checkNumCorrect(mText)) {
        qDebug("[on_WriteAddrTwo_editingFinished] error text:%s",mText.toLocal8Bit().constData());
        QMessageBox::warning(0,"WARNING","ADDRING ERROR!",QMessageBox::Yes);
        return;
    }
}

void Widget::on_RouterAddrOne_editingFinished()
{
    qDebug("[on_RouterAddrOne_editingFinished] edit end!");
    QString mText = ui->RouterAddrOne->text();
    if (!checkNumCorrect(mText)) {
        qDebug("[on_RouterAddrOne_editingFinished] error text:%s",mText.toLocal8Bit().constData());
        QMessageBox::warning(0,"WARNING","Router ADDRING ERROR!",QMessageBox::Yes);
        return;
    }
}

void Widget::on_RouterAddrTwo_editingFinished()
{
    qDebug("[on_RouterAddrTwo_editingFinished] edit end!");
    QString mText = ui->RouterAddrTwo->text();
    if (!checkNumCorrect(mText)) {
        qDebug("[on_WriteAddrTwo_editingFinished] error text:%s",mText.toLocal8Bit().constData());
        QMessageBox::warning(0,"WARNING","Router ADDRING ERROR!",QMessageBox::Yes);
        return;
    }
}

bool Widget::checkNumCorrect(QString& num) {
    if (num.length() == 0) return true;
    if (num.length()>2) {
        return false;
    }
    if (num.length() == 1)
    {
        if ((num[0]>= '0' && num[0] <= '9')||
           (num[0]>= 'a' && num[0] <= 'f')||
            (num[0]>= 'A' && num[0] <= 'F'))
        {
            return true;
        }
    }else{
        if (((num[0]>= '0' && num[0] <= '9')||
           (num[0]>= 'a' && num[0] <= 'f')||
           (num[0]>= 'A' && num[0] <= 'F'))&&
           ((num[1]>= '0' && num[1] <= '9')||
           (num[1]>= 'a' && num[1] <= 'f')||
           (num[1]>= 'A' && num[1] <= 'F')))
        {
            return true;
        }
    }
    return false;
}

/******************定义一个条件变量类控制线程运行*************************/
MessageQueue::MessageQueue(Widget* parent):mWidget(parent),
                mMessageType(MESSAGE_UNKNOW) {

    pthread_mutex_init(&condMutex,0);
    pthread_cond_init(&mCond,0);

}

MessageQueue::~MessageQueue() {
    pthread_mutex_destroy(&condMutex);
    pthread_cond_destroy(&mCond);
}

_S32 MessageQueue::sendMessage(MessageType type) {
    pthread_mutex_lock(&condMutex);
    if (mMessageType != MESSAGE_UNKNOW) {
        pthread_mutex_unlock(&condMutex);
        qDebug("mMessageType not is unknow! do not signal!");
        return FAILURE;
    }
    mMessageType = type;
    pthread_cond_signal(&mCond);
    pthread_mutex_unlock(&condMutex);
    return SUCCESS;
}

MessageQueue::MessageType MessageQueue::waitMessage() {
    pthread_mutex_lock(&condMutex);
    mMessageType = MESSAGE_UNKNOW;
    pthread_cond_wait(&mCond,&condMutex);  //解除阻塞的线程
    pthread_mutex_unlock(&condMutex);
    return mMessageType;
}

bool MessageQueue::messageIsBusy() {
    pthread_mutex_lock(&condMutex);
    if (mMessageType != MESSAGE_UNKNOW) {
        pthread_mutex_unlock(&condMutex);
        qDebug("[messageIsBusy] thread is busy! do not response!");
        return true;
    }
    pthread_mutex_unlock(&condMutex);
    return false;
}

/******************wrok thread**************************************/

WorkThread::WorkThread(Widget* parent):mWidget(parent),running(false) {

}

WorkThread::~WorkThread() {
    if (isRunning()) {
        running = false;
        mWidget->mMessageQueue->sendMessage(MessageQueue::MESSAGE_EXIT);
        wait();
    }
}

void WorkThread::startWork() {
    running = true;
    start();
}

void WorkThread::run() {
    MessageQueue::MessageType mType = MessageQueue::MESSAGE_UNKNOW;

    do {
        qDebug("the thread id is %u",(_U32)QThread::currentThreadId());
        mType = mWidget->mMessageQueue->waitMessage();
        switch(mType) {
            case MessageQueue::MESSAGE_CONNECT : {
                qDebug("[run] MESSAGE_CONNECT!");
            }
            break;
            case MessageQueue::MESSAGE_RESET : {
                qDebug("[run] MESSAGE_RESET!");
            }
            break;
            case MessageQueue::MESSAGE_WRITE_ARG : {
                qDebug("[run] MESSAGE_WRITE_ARG!");
            }
            break;
            case MessageQueue::MESSAGE_READ_INFO : {
                qDebug("[run] MESSAGE_READ_INFO!");
            }
            break;
            case MessageQueue::MESSAGE_EXIT : {
                qDebug("[run] MESSAGE_EXIT!");
                goto end;
            }
            break;
            default: {
                qDebug("[run] default!");
            }
            break;
        }
        sleep(3);
    }while(running);
end:
    qDebug("[run] run exit");
}
